package com.ruoyi.web.controller.box;


import java.io.*;
import java.net.URLEncoder;
import java.util.*;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.alibaba.excel.EasyExcelFactory;
import com.alibaba.excel.ExcelWriter;
import com.alibaba.excel.write.metadata.WriteSheet;
import com.alibaba.excel.write.metadata.fill.FillWrapper;
import com.itextpdf.kernel.font.PdfFont;
import com.itextpdf.kernel.font.PdfFontFactory;
import com.itextpdf.kernel.pdf.PdfDocument;
import com.itextpdf.kernel.pdf.PdfWriter;
import com.itextpdf.layout.Document;
import com.itextpdf.layout.element.Table;
import com.itextpdf.layout.properties.TextAlignment;
import com.itextpdf.layout.properties.UnitValue;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.system.domain.TDeviceInfo;
import com.ruoyi.system.service.ISysConfigService;
import com.ruoyi.system.service.ITDeviceInfoService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.util.ResourceUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.system.domain.TBoxInfo;
import com.ruoyi.system.service.ITBoxInfoService;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.common.core.page.TableDataInfo;



/**
 * 装箱管理Controller
 * 
 * @author ruoyi
 * @date 2024-12-20
 */
@RestController
@RequestMapping("/system/box")
public class TBoxInfoController extends BaseController
{
    @Autowired
    private ITBoxInfoService tBoxInfoService;
    @Autowired
    private ITDeviceInfoService tDeviceInfoService;
    @Autowired
    private ISysConfigService configService;

    @Value("${pdf-path.file}")
    private String pdfPath;
    @Value("${pdf-path.excel}")
    private String excelPath;
    @Value("${pdf-path.font}")
    private String fontPath;

    /**
     * 查询装箱管理列表
     */
    @GetMapping("/list")
    public TableDataInfo list(TBoxInfo tBoxInfo)
    {
        startPage();
        List<TBoxInfo> list = tBoxInfoService.selectTBoxInfoList(tBoxInfo);
        return getDataTable(list);
    }

    /**
     * 导出装箱管理列表
     */
    @PostMapping("/export")
    public void export(HttpServletResponse response, TBoxInfo tBoxInfo)
    {
        List<TBoxInfo> list = tBoxInfoService.selectTBoxInfoList(tBoxInfo);
        ExcelUtil<TBoxInfo> util = new ExcelUtil<TBoxInfo>(TBoxInfo.class);
        util.exportExcel(response, list, "装箱管理数据");
    }

    /**
     * 获取装箱管理详细信息
     */
    @GetMapping(value = "/{boxCode}")
    public AjaxResult getInfo(@PathVariable("boxCode") String boxCode)
    {
        return success(tBoxInfoService.selectTBoxInfoByBoxCode(boxCode));
    }

    /**
     * 新增装箱管理接口（无参）
     */
    @PostMapping("add")
    public AjaxResult add()
    {
        return AjaxResult.success(tBoxInfoService.insertTBoxInfo(null,0));
    }

    /**
     * 新增装箱管理
     */
    @PostMapping
    public AjaxResult add(@RequestBody TBoxInfo tBoxInfo)
    {
        return AjaxResult.success(tBoxInfoService.insertTBoxInfo(tBoxInfo,1));
    }

    /**
     * 修改装箱管理
     */
    @PutMapping
    public AjaxResult edit(@RequestBody TBoxInfo tBoxInfo)
    {
        return toAjax(tBoxInfoService.updateTBoxInfo(tBoxInfo));
    }

    /**
     * 删除装箱管理
     */
	@DeleteMapping("/{boxCodes}")
    public AjaxResult remove(@PathVariable String[] boxCodes)
    {
        return toAjax(tBoxInfoService.deleteTBoxInfoByBoxCodes(boxCodes));
    }
    /**
     * 批量出库
     * @param boxCodes
     * @param tBoxInfo
     * @return
     */
    @PostMapping ("ckBox/{boxCodes}")
    public AjaxResult ckBox(@PathVariable("boxCodes") String[] boxCodes,@RequestBody TBoxInfo tBoxInfo)

    {
        if (StringUtils.isBlank(tBoxInfo.getCustomerInfo())){
            tBoxInfo.setCustomerInfo("");
        }
        if (StringUtils.isBlank(tBoxInfo.getCustomerRemark())){
            tBoxInfo.setCustomerRemark("");
        }
        return toAjax(tBoxInfoService.ckBoxInfoByBoxCodes(tBoxInfo,boxCodes));
    }


    /**
     * type=1 批量封箱
     * @param boxCodes
     * @return
     */
    @PostMapping ("fxCkBox/{boxCodes}/{type}")
    public AjaxResult fxBox(@PathVariable("boxCodes") String[] boxCodes,@PathVariable("type") String type)
    {
        return toAjax(tBoxInfoService.fxBoxInfoByBoxCodes(boxCodes));
    }

    /**
     * 导出PDF文件
     * @date 2024/12/22 21:16
     */
    @PostMapping("export/pdf/{boxCode}")
    public void exportPDF(HttpServletResponse response, @PathVariable("boxCode") String boxCode) throws Exception {

        TBoxInfo tBoxInfot = tBoxInfoService.selectTBoxInfoByBoxCode(boxCode);
        TDeviceInfo tDeviceInfo = new TDeviceInfo();
        tDeviceInfo.setBoxCode(boxCode);
        List<TDeviceInfo> deviceList = tDeviceInfoService.selectTDeviceInfoList(tDeviceInfo);

        // 加载字体
        PdfFont font = PdfFontFactory.createFont(fontPath);
        String fileName = URLEncoder.encode("test.pdf", "UTF-8");
        // 创建PDF文档
        PdfWriter writer = new PdfWriter(pdfPath);
        PdfDocument pdf = new PdfDocument(writer);
        Document document = new Document(pdf);
        //配置的pdf标题
        String configStr = configService.selectConfigByKey("box.pdf.title");
        //表头
        Table tableTitle = new Table(UnitValue.createPercentArray(1)).useAllAvailableWidth();
        tableTitle.addCell(StringUtils.isBlank(configStr)?"":configStr);
        tableTitle.setFont(font);
        tableTitle.setBold();
        tableTitle.setTextAlignment(TextAlignment.CENTER);
        document.add(tableTitle);

        //配置的pdf制造商
        String configZzs = configService.selectConfigByKey("box.zzs");
        Table table_zzs= new Table(UnitValue.createPercentArray(1)).useAllAvailableWidth();
        table_zzs.addCell(StringUtils.isBlank(configStr)?"":configZzs);
        table_zzs.setFont(font);
        table_zzs.setTextAlignment(TextAlignment.RIGHT);
        document.add(table_zzs);

        // 箱子主要信息：创建一个简单的4列表格
        Table table0= new Table(UnitValue.createPercentArray(4)).useAllAvailableWidth();
        table0.addCell("箱号");
        table0.addCell("数量");
        table0.addCell("装箱人");
        table0.addCell("时间");
        table0.setFont(font);
        table0.setBold();
        table0.setTextAlignment(TextAlignment.CENTER);
        document.add(table0);


        Table table= new Table(UnitValue.createPercentArray(4)).useAllAvailableWidth();
        table.addCell(tBoxInfot.getBoxCode());
        table.addCell(tBoxInfot.getDeviceCount()+" / "+tBoxInfot.getBoxCapacity());
        table.addCell(tBoxInfot.getCreateName());
        table.addCell(DateUtils.parseDateToStr("yyyy-MM-dd",tBoxInfot.getBoxTime()));
        table.setFont(font);
        table.setTextAlignment(TextAlignment.CENTER);
        document.add(table);

        //设备标题
        Table table1 = new Table(UnitValue.createPercentArray(1)).useAllAvailableWidth();
        table1.addCell("设备清单");
        table1.setFont(font);
        table1.setBold();
        table1.setTextAlignment(TextAlignment.CENTER);
        document.add(table1);
        //设备清单：创建一个简单的4列表格
        Table table2 = new Table(UnitValue.createPercentArray(4)).useAllAvailableWidth();
        for (TDeviceInfo device:deviceList) {
            table2.addCell(device.getDeviceCode());
        }
        table2.setTextAlignment(TextAlignment.CENTER);
        table2.setFont(font);
        document.add(table2);
        // 关闭文档
        document.close();
        response.setContentType("application/pdf");
        response.setCharacterEncoding("UTF-8");
        response.setHeader("Content-Disposition", "attachment; filename="+fileName);
        File file = new File(pdfPath);
        InputStream stream = new FileInputStream(file);
        ServletOutputStream out = response.getOutputStream();
        byte buff[] = new byte[1024];
        int length = 0;
        while ((length = stream.read(buff)) > 0) {
            out.write(buff,0,length);
        }
        stream.close();
        out.close();
        out.flush();

    }

    /**
     * 按模板-导出Excel文件
     * @date 2024/12/22 21:16
     */
    @PostMapping("export/excel/{boxCode}")
    public void exportExcel(HttpServletResponse response,@PathVariable("boxCode") String boxCode) throws Exception{
        TBoxInfo tBoxInfo = tBoxInfoService.selectTBoxInfoByBoxCode(boxCode);
        String configTitle = configService.selectConfigByKey("box.pdf.title");
        String configZzs = configService.selectConfigByKey("box.zzs");
        Map<String, Object> dataMap = new HashMap<>();
        dataMap.put("boxTitle",configTitle);
        dataMap.put("boxZzs",configZzs);
        dataMap.put("boxCode",tBoxInfo.getBoxCode());
        dataMap.put("boxNum",tBoxInfo.getDeviceCount()+" / "+tBoxInfo.getBoxCapacity());
        dataMap.put("boxUser",tBoxInfo.getCreateName());
        dataMap.put("boxTime",tBoxInfo.getBoxTime());
        List<Map<String, Object>> dataList = new ArrayList<>();
        TDeviceInfo tDeviceInfo = new TDeviceInfo();
        tDeviceInfo.setBoxCode(boxCode);
        List<TDeviceInfo> deviceList = tDeviceInfoService.selectTDeviceInfoList(tDeviceInfo);
        for (int a=0;a<deviceList.size();a+=4) {
            LinkedHashMap<String, Object> item = new LinkedHashMap<>();
            item.put("code1",deviceList.get(a).getDeviceCode());
            item.put("code2",deviceList.get(a+1).getDeviceCode());
            item.put("code3",deviceList.get(a+2).getDeviceCode());
            item.put("code4",deviceList.get(a+3).getDeviceCode());
            dataList.add(item);
        }
        for (int a=0;a<deviceList.size();a+=4) {
            if (a<=deviceList.size()-1){
                LinkedHashMap<String, Object> item = new LinkedHashMap<>();
                item.put("code1",deviceList.get(a).getDeviceCode());

                if (a+1<=deviceList.size()-1){
                    item.put("code2",deviceList.get(a+1).getDeviceCode());
                }else{
                    item.put("code2","");
                }
                if (a+2<=deviceList.size()-1){
                    item.put("code3",deviceList.get(a+2).getDeviceCode());
                }else{
                    item.put("code3","");
                }
                if (a+3<=deviceList.size()-1){
                    item.put("code4",deviceList.get(a+3).getDeviceCode());
                }else{
                    item.put("code4","");
                }
                dataList.add(item);
            }
        }
        // 设置响应头
        response.setContentType("application/vnd.ms-excel");
        response.setCharacterEncoding("utf-8");
        String fileName = URLEncoder.encode("数据导出", "UTF-8").replaceAll("\\+", "%20");
        response.setHeader("Content-disposition", "attachment;filename=" + fileName + ".xlsx");

        //在resources/excel下面放的模板文件
        //File file = new File(excelPath);
        File file = ResourceUtils.getFile("classpath:file-template/zx_template.xlsx");
        // 使用 EasyExcel 填充模板数据并写入第二个 Sheet 页
        try (FileInputStream templateFileStream = new FileInputStream(file);
             ExcelWriter excelWriter = EasyExcelFactory.write(response.getOutputStream()).withTemplate(templateFileStream).build()) {
            // 创建并写入第一个 Sheet（使用模板）
            WriteSheet oneSheet1 = EasyExcelFactory.writerSheet(0).sheetName("sheet1").build();
            //模板里的字段是 device.code
            excelWriter.fill(new FillWrapper("device", dataList), oneSheet1);
            excelWriter.fill(dataMap, oneSheet1);
            // 完成写入
            excelWriter.finish();
        }

    }

    public static void main(String[] args) {
        List<Map<String, Object>> dataList = new ArrayList<>();
        List<String> list = new ArrayList<>();
        list.add("0001");list.add("0002");list.add("0003");list.add("0004");list.add("0005");
        for (int a=0;a<list.size();a+=4) {
            if (a<=list.size()-1){
                LinkedHashMap<String, Object> item = new LinkedHashMap<>();
                item.put("code1","a-"+list.get(a));
                System.out.println("a: "+list.get(a));
                if (a+1<=list.size()-1){
                    System.out.println("a+1: "+list.get(a+1));
                    item.put("code2","a-"+list.get(a+1));
                }else{
                    System.out.println("a+1: ");
                    item.put("code2","");
                }
                if (a+2<=list.size()-1){
                    System.out.println("a+2: "+list.get(a+2));
                    item.put("code3","a-"+list.get(a+2));
                }else{
                    System.out.println("a+2: ");
                    item.put("code3","");
                }
                if (a+3<=list.size()-1){
                    System.out.println("a+3: "+list.get(a+3));
                    item.put("code4","a-"+list.get(a+3));
                }else{
                    System.out.println("a+3: ");
                    item.put("code4","");
                }
                dataList.add(item);
            }
        }
        System.out.println(dataList);
    }
}
